/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.ShopSubagentDto;
import com.yami.shop.bean.model.ShopSubagent;
import com.yami.shop.dao.ShopSubagentMapper;
import com.yami.shop.service.ShopSubagentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 下级代理列表Service实现类
 */
@Service
public class ShopSubagentServiceImpl extends ServiceImpl<ShopSubagentMapper, ShopSubagent> implements ShopSubagentService {

    @Autowired
    private ShopSubagentMapper shopSubagentMapper;

    @Override
    public IPage<ShopSubagent> getShopSubagentsByShopId(Page page, Long shopId) {
        return shopSubagentMapper.getShopSubagentsByShopId(page, shopId);
    }

    @Override
    public IPage<ShopSubagentDto> getShopSubagentsWithDetailByShopId(Page page, Long shopId) {
        return shopSubagentMapper.getShopSubagentsWithDetailByShopId(page, shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addShopSubagent(ShopSubagent shopSubagent) {
        // 检查是否已存在相同的代理关系
        LambdaQueryWrapper<ShopSubagent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopSubagent::getShopId, shopSubagent.getShopId())
                .eq(ShopSubagent::getSubShopId, shopSubagent.getSubShopId());
        
        int count = this.count(wrapper);
        if (count > 0) {
            return false;
        }
        
        // 设置默认值
        shopSubagent.setCreateTime(new Date());
        shopSubagent.setUpdateTime(new Date());
        if (shopSubagent.getAuditStatus() == null) {
            shopSubagent.setAuditStatus(0); // 默认待审核
        }
        
        return this.save(shopSubagent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAuditStatus(Long id, Integer auditStatus, String remarks) {
        ShopSubagent shopSubagent = this.getById(id);
        if (shopSubagent == null) {
            return false;
        }
        
        shopSubagent.setAuditStatus(auditStatus);
        shopSubagent.setRemarks(remarks);
        shopSubagent.setUpdateTime(new Date());
        
        return this.updateById(shopSubagent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteShopSubagent(Long id) {
        return this.removeById(id);
    }
} 